package com.idemon.task;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 自动配置
 *
 * @author idemon
 * @since 2020-09-06 17:08
 */
@Configuration
@EnableScheduling
public class SchedulerConfiguration {
    /**
     * 向spring容器注入配置好的Scheduler线程池
     * @return TaskScheduler
     */
    @Bean
    public TaskScheduler getTaskScheduler(){
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        // 池大小
        threadPoolTaskScheduler.setPoolSize(Runtime.getRuntime().availableProcessors() / 3 + 1);
        // 名字前缀
        threadPoolTaskScheduler.setThreadNamePrefix("TaskScheduler-");
        // 是否等待执行任务完毕后关闭
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        // 再关闭的时候等待其他task完成的最长等待时间
        threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
        // 保证能立刻丢弃运行中的任务
        threadPoolTaskScheduler.setRemoveOnCancelPolicy(true);
        return threadPoolTaskScheduler;
    }

    /**
     * spring在卸载（销毁）实例时，关闭线程或线程池
     * @return
     */
    @Bean
    public DisposableBean getThreadPoolTaskSchedulerDisposable(){
        return () -> {
            ((ThreadPoolTaskScheduler)getTaskScheduler()).shutdown();
        };
    }
}